//
//  SIXSearchTableViewController.m
//  weibo
//
//  Created by   李小云 on 16/5/20.
//  Copyright © 2016年 chuhan. All rights reserved.
//

#import "SIXSearchTableViewController.h"
#import "SIXFieldView.h"
#import "Masonry.h"
#define fontCOLOR [UIColor colorWithRed:163/255.0f green:163/255.0f blue:163/255.0f alpha:1]
@interface SIXSearchTableViewController ()<UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *searchField;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
//历史记录
@property (nonatomic,strong)NSMutableArray * searchHistory;

@property (nonatomic,strong)NSArray *myArray;//搜索记录的数组

@property (weak, nonatomic) IBOutlet UIView *navView;

@end

@implementation SIXSearchTableViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:NO];
    [self readNSUserDefaults];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    //设置搜索记录文字后面的cell为空 不显示
     self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

    _searchHistory = [NSMutableArray array];
   
    _searchField.delegate = self;
    _searchField.clearButtonMode = UITextFieldViewModeWhileEditing;
 
}
//当键盘输入的时候 调用
-(BOOL)textFieldShouldReturn:(UITextField *)textField{//搜索方法
    if (textField.text.length > 0) {
        
        [self SearchText:textField.text];//缓存搜索记录
         textField.text = @"";
        //读取全新的数据 刷新并刷新界面
        [self readNSUserDefaults];
        
    }else{
        //如果输入为空,提示重新输入
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"输入为空,请重新输入" message:@"" preferredStyle: UIAlertControllerStyleAlert];
        [self presentViewController:alertController animated:YES completion:nil];
        
        [UIView animateWithDuration:0.5 animations:^{
            
        [self dismissViewControllerAnimated:alertController completion:nil];
        }];
    }
    return YES;
}
#pragma mark - tableView代理和数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
        if (_myArray.count>0) {
            return _myArray.count+2;;
        }else{
            return 1;
        }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:@"cell"];
    //设置底部和头部文字
    if (indexPath.section==0) {
        if(indexPath.row ==0){
            cell.textLabel.text = @"历史搜索";
            cell.textLabel.textColor = fontCOLOR;
            return cell;
        }else if (indexPath.row == _myArray.count+1){
            cell.textLabel.text = @"清除历史记录";
            cell.textLabel.textColor = fontCOLOR;
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            return cell;
        }
        //当row不为零时显示数组内容
        else{
            //把数组遍历反向存储
            NSArray* reversedArray = [[_myArray reverseObjectEnumerator] allObjects];
            cell.textLabel.text = reversedArray[indexPath.row-1];
            return cell;
        }
    }else{
        return cell;
    }
}
//设置cell的估算高度 然后让其自己计算
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    self.tableView.estimatedRowHeight = 44.0f;
    return UITableViewAutomaticDimension;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == _myArray.count+1) {//清除所有历史记录
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"清除历史记录" message:@"" preferredStyle: UIAlertControllerStyleAlert];
        
        //@“ UIAlertControllerStyleAlert，改成这个就是中间弹出"
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self removeAllArray];
            _myArray = nil;
            [self.tableView reloadData];
        }];
    
        [alertController addAction:cancelAction];
        [alertController addAction:deleteAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}


-(void)readNSUserDefaults{//取出缓存的数据
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSArray * myArray = [userDefaultes arrayForKey:@"myArray"];
    self.myArray = myArray;
    [self.tableView reloadData];

}

//缓存搜索数组
-(void)SearchText :(NSString *)seaTxt
{
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //先读取缓存的数据
    NSArray *myArray = [userDefaultes arrayForKey:@"myArray"];
    if (myArray.count > 0) {//先取出数组，判断是否有值，有值继续添加，无值创建数组
        
    }else{
        myArray = [NSArray array];
    }
    
    NSMutableArray *searTXT = [myArray mutableCopy];
    [searTXT addObject:seaTxt];
    //设置数据上限,如果不设置 清除搜索历史就无法看到了
    if(searTXT.count > 15)
    {
        [searTXT removeObjectAtIndex:0];
    }
    //将上述数据全部存储到NSUserDefaults中
    [userDefaultes setObject:searTXT forKey:@"myArray"];
}
-(void)removeAllArray{
    //偏好设置 取出所有数据 把数据删除
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults removeObjectForKey:@"myArray"];
    
}



- (IBAction)btnClick:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


@end
